<?php
namespace Home\Model;
use Think\Model;
class PostModel extends Model {
    public $lastError;
    protected $errorCode;
    public function index()
    {

    }

    /*
     * 根据条件显示数组
     */
    public function getPostList($con = [], $field = '*', $limit = '*')
    {
        $list = $this->where($con)->field($field)->limit($limit)->select();
        foreach ($list as $k => $v) {

            $list[$k] = $this->parseRow($v);
            // $userIdArr[] = $v['user_id'];
        }
        return $list;
    }

    /*
     * @param array $list 需要添加信息的数组
     */
    public function parseUserList($list)
    {
        $userMod = D('User');
        $userIdArr = array_column($list, 'user_id');
        $userList = [];
        if (!empty($userIdArr)) {
            //查询user表信息，获取id与$userIdArr中的user_id相等的数据，并保存到$userList中
            $con = ['id' => ['in', $userIdArr]];
            //$userList = $userMod->where($con)->select();
            $userList =  $userMod->where($con)->select();
        }

        //再次遍历list，将name,avatar信息添加到list中
        foreach($list as $k => $v) {
            $userId = $v['user_id'];
            foreach ($userList as $key => $value) {
                if ($value['id'] == $userId) {
                    $v['name'] = $value['name'];

                    if (mb_substr($value['avatar'],0,4) == 'uplo' && !empty($value['avatar'])) {
                        $value['avatar'] = "http://tieba_with_think.cc/public/images/".substr($value['avatar'], 7);
                    }
                    $v['avatar'] = $value['avatar'];
                }
            }
            $list[$k] = $v;
        }
        return $list;
    }

    /*
     * @param array $v 需要格式化的数组
     */
    public function parseRow($v)
    {
        $v['id'] = (int)$v['id'];
        $v['img'] = explode(",", $v['img']);
            foreach ($v['img'] as $key => $value) {
                if (!empty($value) && mb_substr($v['img'][$key],0,4) != 'http') {
                    $v['img'][$key] = "http://tieba_with_think.cc/public/images/".$v['img'][$key];
            }
        }

        $v['addTime'] = date("h:i", $v['add_time']);
        if ($v['update_time'] == 0) {
            $v['updateTime'] = '0';
        } else {
            $v['updateTime'] = date("h:i", $v['update_time']);
        }
        return $v;
    }

    /**
     * 带分页的列表
     * @param array $con
     * @param int $perNum
     * @param string $orderBy
     * @return array
     */
    public function getPageList($con, $perNum = 15, $orderBy = 'update_time desc')
    {
        //数据分页
        $count = $this->where($con)->count();
        $perNum = (int)$_GET['perNum'];
        if(!$perNum) $perNum = 10;
        $p = new \Think\Page($count, $perNum);

        $list = $this->where($con)->limit($p->firstRow.','.$p->listRows)->select();
        $pageVar = $p -> show();
        $list = $this->parseUserList($list);
        //给list添加新的字段
        foreach ($list as $k => $v) {
            $list[$k] = $this->parseRow($v);
            if ($v['img'][0] == "") {
                $list[$k]['imgLength'] = 0;
            } else {
                $v['img'] = explode(",", $v['img']);
                $list[$k]['imgLength'] = count($v['img']);
            }
            $list[$k]['replyNum'] = 50;
        }
        $cur = $_GET['p'];
        !$cur && $cur = 1;
        return [
            'list' => $list,
            'total' => (int)$p -> totalRows,
            'page' => (int)$p -> totalPages,
            'cur' => $cur,
            'pageVar' => $pageVar
        ];
    }

    /**
     * 帖子详情
     * @param $postId
     * @return array
     */
    public function getDetail($postId)
    {
        $con = "id='$postId'";
        $post = $this->where($con)->find();
        $post = $this->parseRow($post);
        $post = $this->parseUserList([$post])[0];
        return $post;
    }

    /**
     * 帖子列表
     * @param array $con
     * @param string $orderBy
     * @param int $limit
     * @return array
     */
    public function getList($con, $orderBy = 'id desc', $limit = 10)
    {
        //实例化Post模型类和User模型类
        $postMod = D('Post');;
        $con = ['title' => ['like', $con]];
        $topList = $postMod->where($con)->field('id,title')->limit($limit)->select();

        foreach ($topList as $k => &$v) {
            $v['id'] = (int)$v['id'];
        }
        return $topList;
    }

    /**
     * 发布帖子
     * @param $title
     * @param $content
     * @param $userId
     * @return array|bool
     */
    public function addPost($title, $content, $userId)
    {
        if (!$userId) {
            return $this->setError('未登录');
        } else {
            $user_id = session('user.id');
            $img = $this->upload();
            if (empty($title) || empty($content)) {
                return $this->setError('标题和内容不能为空!');
            }
            $data = [
                'user_id' => $user_id,
                'title' => $title,
                'content' => $content,
                'add_time' => time(),
                'img' => $img
            ];

            if ($id = $this->add($data)) {
                $info = $this->getInfo($id);
                return $info;
            }

        }
        return false;
    }

    public function getInfo($id, $field = '*')
    {
        $id = (int)$id;
        $info = $this->field($field)->find($id);
        if (!$info) return [];
        return $this->parseRow($info);
    }

    /**
     * 上传文件
     * @return string
     */
    public function upload()
    {
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize   =     5145728 ;// 设置附件上传大小
        $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->rootPath  =     './Public/images/'; // 设置附件上传根目录
        $upload->savePath  =     ''; // 设置附件上传（子）目录
        $upload->saveName = '';
        $upload->autoSub = false;
        $upload->replace = true;
        // 上传文件
        $info   =   $upload->upload();
        $imgUrl = '';
//        if(!$info) {// 上传错误提示错误信息
//            echo 'sss';
//        }// 上传成功
            foreach($info as $file){
                if (empty($imgUrl)) {
                    $imgUrl = $file['savepath'].$file['savename'];
                } else {
                    $imgUrl .= ','.$file['savepath'].$file['savename'];
                }
            }
            return $imgUrl;

    }

    /**
     * 编辑(修改)帖子
     * @param $id
     * @param $title
     * @param $content
     * @param $userId
     * @return array|bool
     */
    public function update($id, $title, $content, $userId)
    {
        if (!$userId) {
            return $this->setError('未登录');
        } else {
            $user_id = session('user.id');
            $post_user_id = $this->where("id='$id'")->getField('user_id');
            if ($post_user_id != $user_id) {
                return $this->setError('发帖人才能修改呢!');
            } else {
                $img = $this->upload();
                if (empty($img)) {
                    $data = [
                        'title' => $title,
                        'content' => $content,
                        'update_time' => time()
                    ];
                } else {
                    $data = [
                        'title' => $title,
                        'content' => $content,
                        'update_time' => time(),
                        'img' => $img
                    ];
                }
                $return  = $this->data($data)->where('id=' . (int)$id)->save();
                if(false !== $return){
                    $info = $this->getInfo($id);
                    return $info;
                }
            }
        }
        return false;
    }

    /**
     * 删除帖子
     * @param $id
     * @param $userId
     * @return bool
     */
    public function deletePost($id, $userId)
    {
        if (!$userId) {
            return false;
        } else {
            $post_user_id = $this->where("id='$id'")->getField('user_id');
            $user_id = session('user.id');
            if ($post_user_id != $user_id) {
                return $this->setError('发帖人才能删除呢！');
            } else {
                $this->delete($id);
                D('PostComment')->where("post_li_id='$id'")->delete();
                return true;
            }
        }
    }

    /**
     * 设置错误信息
     * @param $msg
     * @param int $code
     * @param bool $flag
     * @return bool
     */
    protected function setError($msg, $code=1,$flag = false){
        $this->lastError = $msg;
        $this->errorCode = $code;
        return $flag;
    }

    //错误码
    public function getErrorCode(){
        return $this->errorCode;
    }

    public function getError(){
        if($this->lastError)
            return $this->lastError;
        return parent::getError();
    }

}